<template>
  <div class="hello" v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">

      <el-form-item label="标签类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="数量" prop="number">
        <el-input-number v-model="form.number" :min="1" :max="1000" label="数量"></el-input-number>
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="download">下载</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
  import {qrCode} from "@/api/qrCode";

  export default {
    name: 'HelloWorld',
    data() {
      return {
        loading: false,
        form: {
          type: null,
          number: null,
        },
        rules: {
          type: [
            {
              required: true,
              message: '请选择标签类型',
              trigger: 'blur'
            }
          ],
          number: [
            {
              required: true,
              message: '请输入数量',
              trigger: 'blur'
            }
          ]
        },
        options: [
          {
            value: 'Z',
            label: '种子'
          },
          {
            value: 'B',
            label: '标签'
          },
        ]
      }
    },
    methods: {
      download() {
        let that = this;
        this.$refs['form'].validate(valid => {
          if (valid) {
            that.loading = true;
            qrCode(that.form)
              .then(res => {
                if (res.data && res.data.msg) {
                  let fileList = res.data.msg.split('/');
                  const element = document.createElement('a');
                  fetch(res.data.msg).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
                    element.href = URL.createObjectURL(blob);
                    document.body.appendChild(element);
                    element.setAttribute('download', fileList[fileList.length - 1])
                    element.click();
                    that.loading = false;
                  });
                  element.style.display = 'none';
                  element.remove();
                } else {
                  that.$message.error('生成失败');
                  that.loading = false;
                }
              })
          }
        })

      }
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .hello {
    height: max-content;
    width: max-content;
  }
</style>
